package cn.yutong.framework;

import com.google.common.base.Strings;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Expires, Content-Type,Authorization,token");
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpStatus.SC_OK);
            response.getWriter().write("OK");
            return false;
        }


        if (uri.startsWith("/login") || uri.startsWith("/code")||uri.startsWith("/register"))
            return true;


        String userID = request.getHeader("userID");
        if (Strings.isNullOrEmpty(userID)) {
            PrintWriter out = response.getWriter();
            out.append("{\"ret\":997,\"msg\":\"请在HTTP Header中添加'userID'!(登录请求除外) url:" + url
                    + "\"}");
            return false;
        }
        Integer id = Integer.valueOf(userID);
        CacheUser user = UserCache.getUser(id);

        if (user == null) {
            PrintWriter out = response.getWriter();
            out.append("{\"ret\":999,\"msg\":\"用户未登录!  url:" + url + "\"}");
            return false;
        }
        long timeBetween = System.currentTimeMillis() - user.getLastHitTime();
        if (timeBetween > 30 * 60 * 1000) {
//        if (timeBetween > 5 * 1000) {
            PrintWriter out = response.getWriter();
            out.append("{\"ret\":998,\"msg\":\"登录过期,请重新登录! url:" + url + "\"}");
            return false;
        }
        UserCache.touchUser(user.getUid());
        return true;
    }

}
